package logic

import (
	"context"
	"encoding/json"
	"shuqi-novel/cache"
	"shuqi-novel/mysql"
	"shuqi-novel/userrpc/internal/svc"
	"shuqi-novel/userrpc/userrpc"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ArticleListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewArticleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ArticleListLogic {
	return &ArticleListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 小说列表
func (l *ArticleListLogic) ArticleList(in *userrpc.ArticleListRequest) (*userrpc.ArticleListResponse, error) {
	// todo: add your logic here and delete this line

	var list []*userrpc.ArticleList

	key := "article_list"
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		list, _ = mysql.ArticleList(mysql.DB)
		marshal, _ := json.Marshal(list)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*5)
	} else {
		json.Unmarshal([]byte(result), &list)
	}
	return &userrpc.ArticleListResponse{
		List: list,
	}, nil
}
